package com.liu.OrderService.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liu.OrderService.client.EduCourseClient;
import com.liu.OrderService.client.UcenterMemberClient;
import com.liu.OrderService.entity.EduOrder;
import com.liu.OrderService.service.EduOrderService;
import com.liu.R;
import com.liu.entity.CourseAllInfoVo;
import com.liu.entity.UcenterMember;
import com.liu.serviceBase.exception.MyException;
import com.liu.utils.JwtUtils;
import com.liu.utils.OrderNoUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author LSJ
 * @since 2022-02-11
 */
@RestController
@RequestMapping("/OrderService/order")
@CrossOrigin
public class EduOrderController {

    @Autowired
    private EduOrderService eduOrderService;

    //根据课程id和用户id创建订单，返回订单orderId 订单号
    @PostMapping("CreateOrder/{courseId}")
    public R CreateOrder(@PathVariable String courseId, HttpServletRequest request){

        if (ObjectUtils.isEmpty(courseId)){
            throw new MyException(20001,"CreateOrder/{courseId},courseId为空");
        }
        if (ObjectUtils.isEmpty(request)){
            throw new MyException(20001,"CreateOrder/{courseId},request为空，用户未登录！");

        }
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (ObjectUtils.isEmpty(memberId)){
//            return R.error().message("用户未登录");
            return R.error().code(28004).message("用户未登录");
//            throw new MyException(20001,"CreateOrder/{courseId},memberId，用户未登录！");
        }
        String  orderId = eduOrderService.createOrder(courseId,memberId);

        return ObjectUtils.isNotEmpty(orderId)
                ?R.ok().data("orderId",orderId)
                :R.error().message("orderId返回空");

    }

//    根据id获取订单信息接口
    @GetMapping("getOrderByOid/{oid}")
    public R getOrderByOid(@PathVariable String oid){
        QueryWrapper<EduOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",oid);
        EduOrder order = eduOrderService.getOne(wrapper);

//        EduOrder order = eduOrderService.getById(oid);
        return ObjectUtils.isNotEmpty(order)
                ?R.ok().data("order",order)
                :R.error().message("order返回空");

    }

//    根据用户id和课程id 来查询订单的支付状态status

    @GetMapping("getOrderStatus/{memberId}/{courseId}")
    public Boolean getOrderStatus(@PathVariable String memberId,@PathVariable String courseId) {

        QueryWrapper<EduOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id", memberId);
        wrapper.eq("course_id", courseId);
        wrapper.eq("status", 1);
        int count = eduOrderService.count(wrapper);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }
}

